package com.agileai.esb.smc.controller.analysis;

import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.Element;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.esb.smc.bizmoduler.analysis.MessageFlowStatManage;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.XmlUtil;

public class MessageFlowStatChartHandler extends BaseHandler{
	
	public MessageFlowStatChartHandler(){
		super();
	}

	public ViewRenderer prepareDisplay(DataParam param){
		initParameters(param);
		this.setAttributes(param);
		return new LocalRenderer(getPage());
	}
	
    protected void initParameters(DataParam param) {
        initParamItem(param, "sdate", DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, DateUtil.getBeginOfMonth(new Date())));
        initParamItem(param, "edate", DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL, new Date()));
    }    
	@PageAction
	public ViewRenderer query(DataParam param){
		return prepareDisplay(param);
	}
	@PageAction
	public ViewRenderer loadStatData(DataParam param){
		String responseText = null;
		String sdate = param.get("sdate");
		String edate = param.get("edate");
		
		MessageFlowStatManage service = lookupService(MessageFlowStatManage.class);
		List<DataRow> statRecords = service.findStatisticsRecords(sdate, edate);
		responseText = this.buildStatJSON(statRecords);
		return new AjaxRenderer(responseText);
	}
    
	@PageAction
	public ViewRenderer retrieveXml(DataParam param){
		String result = "";
		String infoType = param.get("infoType");
		int topNum = 5;
		String sdate = param.get("sdate");
		String edate = param.get("edate");
		
		MessageFlowStatManage service = lookupService(MessageFlowStatManage.class);
		if(infoType.equals("ActiveMfStat")){
			List<DataRow> activeMfStatRecords = service.findTopActiveRecords(sdate, edate, topNum);
			result = this.buildActiveStatXml(activeMfStatRecords);
		}
		else if (infoType.equals("SlowlyMfStat")){
			List<DataRow> slowlyMfStatRecords = service.findTopSlowlyRecords(sdate, edate, topNum);
			result = this.buildSlowlyStatXml(slowlyMfStatRecords);
		}
		return new AjaxRenderer(result);
	}

	public String buildStatJSON(List<DataRow> statRecords){
		JSONArray jsonArray = new JSONArray();
		try {
	    	for (int i=0;i < statRecords.size();i++){
	    		DataRow row = statRecords.get(i);
	    		JSONObject jsonObject = new JSONObject();
	    		jsonObject.put("appName",row.stringValue("APP_NAME"));
	    		jsonObject.put("messageFlowId",row.stringValue("MF_ID"));
	    		jsonObject.put("messageFlowName",row.stringValue("MF_NAME"));
	    		jsonObject.put("messageFlowAlias",row.stringValue("MF_ALIAS"));
	    		jsonObject.put("messageFlowType",row.stringValue("MF_TYPE"));
	    		jsonObject.put("totalCount",row.stringValue("MF_RUN_COUNT"));
	    		jsonObject.put("successCount",row.stringValue("MF_SUCCESS_COUNT"));
	    		jsonObject.put("failureCount",row.stringValue("MF_ERROR_COUNT"));
	    		jsonObject.put("maxRuntime",row.stringValue("MF_MAX_RUNTIME"));
	    		jsonObject.put("minRuntime",row.stringValue("MF_MIN_RUNTIME"));
	    		long totolRunTime = Long.parseLong(row.stringValue("MF_TOTAL_RUNTIME"));
	    		long totolRunCount = Long.parseLong(row.stringValue("MF_RUN_COUNT"));
	    		jsonObject.put("averageRuntime",totolRunTime/totolRunCount);
	    		jsonArray.put(jsonObject);
	    	}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return jsonArray.toString();
	}
	
	public String buildSlowlyStatXml(List<DataRow> slowlyMfStatRecords){
		Document document = XmlUtil.createDocument();
		Element charElement = document.addElement("chart"); 

		charElement.addAttribute("caption","平均最慢流程统计");
		charElement.addAttribute("yAxisName","运行时间");
		charElement.addAttribute("useRoundEdges","1");
//		charElement.addAttribute("bgColor","FFFFFF,FFFFFF");
		charElement.addAttribute("showBorder","0");
		charElement.addAttribute("legendBorderAlpha","0");
		for (int i=0;i < slowlyMfStatRecords.size();i++){
			DataRow row = slowlyMfStatRecords.get(i);
			Element element = charElement.addElement("set");
			String appName = row.stringValue("APP_NAME");
			element.addAttribute("label",appName+"."+row.stringValue("MF_ALIAS"));
			element.addAttribute("value",row.stringValue("MF_AVERAGE_TIME"));
		}
		return document.asXML().toString();
	}
	
	public String buildActiveStatXml(List<DataRow> activeMfStatRecords){
		Document document = XmlUtil.createDocument();
		Element charElement = document.addElement("chart"); 
		
		charElement.addAttribute("caption","最活跃流程统计");
		charElement.addAttribute("yAxisName","运行次数");
		charElement.addAttribute("useRoundEdges","1");
		charElement.addAttribute("showLabels","1");
//		charElement.addAttribute("bgColor","FFFFFF,FFFFFF");
		charElement.addAttribute("showvalues","0");
		charElement.addAttribute("decimals","0");
		charElement.addAttribute("legendBorderAlpha","0");
		
		Element categoriesElement = charElement.addElement("categories");
		
		Element successElement = charElement.addElement("dataset");
		successElement.addAttribute("seriesName", "成功次数");
		successElement.addAttribute("color", "F6BD0F");
		successElement.addAttribute("showValues", "0");
		
		Element failureElement = charElement.addElement("dataset");
		failureElement.addAttribute("seriesName", "失败次数");
		failureElement.addAttribute("color", "8BBA00");
		failureElement.addAttribute("showValues", "0");
		
		for (int i=0;i < activeMfStatRecords.size();i++){
			DataRow row = activeMfStatRecords.get(i);
			String appName = row.stringValue("APP_NAME");
			Element element = categoriesElement.addElement("category");
			element.addAttribute("label",appName+"."+row.stringValue("MF_ALIAS"));
		}
		
		
		for (int i=0;i < activeMfStatRecords.size();i++){
			DataRow row = activeMfStatRecords.get(i);
			Element element = successElement.addElement("set");
			element.addAttribute("value",row.stringValue("MF_SUCCESS_COUNT"));
		}
		
		for (int i=0;i < activeMfStatRecords.size();i++){
			DataRow row = activeMfStatRecords.get(i);
			Element element = failureElement.addElement("set");
			element.addAttribute("value",row.stringValue("MF_ERROR_COUNT"));
		}		
		
		return document.asXML().toString();
	}	
}